package Thread;

/*线程池
线程池主要有两个作用:
1:重用线程
2:控制线程数量
当我们的应用需要创建大量线程或者发现线程
会频繁的创建和销毁时就应当考虑使用线程池
来维护线程。*/

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolDemo1 {
    public static void main(String[] args) {
        ExecutorService threadPool= Executors.newFixedThreadPool(2);

        for (int i = 0; i < 5; i++) {
            Runnable runnable=new Runnable() {
                @Override
                public void run() {
                    Thread thread=Thread.currentThread();
                    System.out.println(thread+"正在执行");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
//                    System.out.println(thread+"执行结束");
                }
            };
            threadPool.execute(runnable);
        }

        threadPool.shutdown();  //有任务就不会终止 等任务全部结束后在停止
//        threadPool.shutdownNow(); //不管任务结束没结束 都会停止

    }
}
